package top.soft.windows;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import top.soft.util.CommonData;
import top.soft.util.NetWork;
import top.soft.util.Request;
import top.soft.util.Response;

/**
 * @ClassName: UploadView
 * @Author: Amosen
 * @Since: 2021/4/21
 */

// 这个类用于文件选项卡，给予下载文件和上传文件的功能
public class FileView extends JPanel {

	private TableModel tableModel;

	private JFileChooser fileChooser;

	private JTable fileTable;

	private JTextField selectedFileBar;

	private JButton chooseBtn, resetBtn, uploadBtn, refreshBtn, downloadBtn;

	private JComboBox<String> authSelectBox;

	public FileView() {
		init();
	}

	private void init() {
		// 准备表格数据
		getData();

		// 准备表格组件
		setTable();

		// 准备按钮和文件展示框按钮
		selectedFileBar = new JTextField(15);
		chooseBtn = new JButton(CommonData.CHOOSE_BTN);
		resetBtn = new JButton(CommonData.RESET_BTN);
		uploadBtn = new JButton(CommonData.UPLOAD_BTN);
		refreshBtn = new JButton(CommonData.REFRESH_BTN);
		downloadBtn = new JButton(CommonData.DOWNLOAD_BTN);

		// 准备下拉列表
		authSelectBox = new JComboBox<String>(CommonData.AUTH_SELECT_BOX);

		// 添加事件
		chooseBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				doChoose();
			}
		});

		resetBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				doReset();
			}
		});

		uploadBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				doUpload();
			}
		});

		refreshBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				doRefresh();
			}
		});

		downloadBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				doDownload();
			}
		});

		// 添加组件
		setLayout(new BorderLayout());
		JScrollPane scrollPane = new JScrollPane(fileTable);
		add(scrollPane, BorderLayout.CENTER);
		JPanel panelSouth = new JPanel();
		panelSouth.setLayout(new FlowLayout());
		panelSouth.add(selectedFileBar);
		panelSouth.add(authSelectBox);
		panelSouth.add(chooseBtn);
		panelSouth.add(resetBtn);
		panelSouth.add(uploadBtn);
		panelSouth.add(refreshBtn);
		panelSouth.add(downloadBtn);
		add(panelSouth, BorderLayout.SOUTH);
	}

	private void getData() {
		Request request = new Request();
		request.setMethod(Request.GET);
		request.setUrl(CommonData.FILE_LIST_PATH);
		Response response = NetWork.service(request);
		if (response == null) {
			JOptionPane.showMessageDialog(null, "网络连接失败！");
			return;
		} else {
			try {
				List<LinkedHashMap<String, Object>> filelist = (List<LinkedHashMap<String, Object>>) response.getData()
						.get("files");
				// 封装到二维数组中
				String[][] result = new String[CommonData.FILE_TABLE_COLUMNS_NUM][filelist.size()];
				int i = 0;
				for (LinkedHashMap<String, Object> file : filelist) {
					String[] fileData = new String[CommonData.FILE_TABLE_COLUMNS_NUM];
					fileData[0] = String.valueOf(file.get("id"));
					fileData[1] = (String) file.get("fileName");
					fileData[2] = (String) file.get("fileType");
					fileData[3] = String.valueOf(file.get("fileSize"));
					fileData[4] = (String) file.get("uploader");
					fileData[5] = String.valueOf(file.get("downloadTimes"));
					fileData[6] = String.valueOf(file.get("downloadAuth"));
					result[i] = fileData;
					i++;
				}
				CommonData.fileData = result;
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}

	}

	private void setTable() {
		if (fileTable == null) {
			fileTable = new JTable();
		}
		tableModel = new DefaultTableModel(CommonData.fileData, CommonData.FILE_TABLE_HEADER);
		fileTable.setModel(tableModel);
		fileTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	}

	// 选择文件
	private void doChoose() {
		fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.showDialog(new JLabel(), "选择文件");
		File selectedFile = fileChooser.getSelectedFile();
		if (selectedFile == null) {
			return;
		} else {
			String filePath = selectedFile.getAbsolutePath();
			selectedFileBar.setText(filePath);
		}
	}

	// 重置文件选择
	private void doReset() {
		fileChooser = new JFileChooser();
		selectedFileBar.setText("");
	}

	// 上传文件
	private void doUpload() {
		String selectedFilePath = selectedFileBar.getText();
		if (selectedFilePath == null) {
			return;
		} else if ("".equals(selectedFilePath) || selectedFilePath.trim().length() == 0) {
			return;
		} else {
			int selectAuthIndex = authSelectBox.getSelectedIndex();
			int selectAuth;
			if (selectAuthIndex == 0) {
				selectAuth = CommonData.COMMON_AUTH;
			} else if (selectAuthIndex == 1) {
				selectAuth = CommonData.MANAGER;
			} else if (selectAuthIndex == 2) {
				selectAuth = CommonData.ROOT;
			} else {
				selectAuth = CommonData.COMMON_AUTH;
			}
			Request request = new Request();
			request.addData("uploader", CommonData.getUser().getAccount());
			request.addData("downloadAuth", String.valueOf(selectAuth));
			request.setUrl(CommonData.UPLOAD_FILE_PATH);
			Response response = NetWork.uploadFile(request, selectedFilePath);
			if (response == null) {
				JOptionPane.showMessageDialog(null, "IO异常，请检查文件或网络后重试！");
			} else {
				if (response.getCode() == 505) {
					JOptionPane.showMessageDialog(null, "文件上传失败！");
					return;
				} else if (response.getCode() == 200) {
					JOptionPane.showMessageDialog(null, "上传成功！");
					return;
				}
			}
		}
	}

	// 刷新表格
	private void doRefresh() {
		getData();
		setTable();
	}

	// 下载文件
	private void doDownload() {
		int selectedRow = fileTable.getSelectedRow();
		if (selectedRow == -1) {
			return;
		} else {
			fileChooser = new JFileChooser();
			fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			fileChooser.showDialog(new JLabel(), "选择文件夹");
			File selectedFile = fileChooser.getSelectedFile();
			if (selectedFile == null) {
				return;
			}
			if (!selectedFile.isDirectory()) {
				return;
			} else {
				String localPath = selectedFile.getAbsolutePath();
				String fileName = (String) fileTable.getModel().getValueAt(selectedRow, 1);
				String fileIdStr = (String) fileTable.getModel().getValueAt(selectedRow, 0);
				Integer fileId = Integer.valueOf(fileIdStr);
				try {
					Response response = NetWork.downloadFile(CommonData.DOWNLOAD_PATH, localPath + "/" + fileName,
							fileId);
					if (response == null) {
						JOptionPane.showMessageDialog(null, "IO异常，请检查后重试");
						return;
					} else {
						if (response.getCode() == 504) {
							JOptionPane.showMessageDialog(null, "您没有访问权限！");
							return;
						} else if (response.getCode() == 200) {
							return;
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
					JOptionPane.showMessageDialog(null, "文件下载失败！");
					e.printStackTrace();
				}
			}

		}

	}

}
